package com.hongtech.modules.app.controller;

import com.hongtech.common.bean.AjaxResultVo;
import com.hongtech.framework.config.OssConfig;
import com.hongtech.modules.app.annotation.AppLogin;
import com.hongtech.modules.app.dto.UserDTO;
import com.hongtech.modules.app.form.AuthForm;
import com.hongtech.modules.app.form.EditPasswordForm;
import com.hongtech.modules.app.form.LoginForm;
import com.hongtech.modules.app.service.UserService;
import com.hongtech.modules.app.utils.JwtUtils;
import com.hongtech.modules.knowledge.dto.AuthDTO;
import com.hongtech.modules.knowledge.service.AuthService;
import com.hongtech.modules.oss.OssFactory;
import com.hongtech.modules.oss.OssService;
import com.hongtech.modules.oss.SysUploadFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * APP登录授权
 */
@RestController
@RequestMapping("/app")
@Api(tags = "APP登录接口")
public class AppLoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private OssConfig ossConfig;

    @Autowired
    private AuthService authService;

    @PostMapping("login")
    @ApiOperation("登录")
    public AjaxResultVo login(@RequestBody LoginForm form) {
        UserDTO user = userService.queryByMobile(form.getMobile());
        if (ObjectUtils.isEmpty(user)) {
            return AjaxResultVo.error("手机号或密码错误");
        }
        //密码错误
        if (!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))) {
            return AjaxResultVo.error("手机号或密码错误");
        }
        //返回屏蔽密码字段
        user.setPassword(null);
        //生成token
        String token = jwtUtils.generateToken(user.getUserId());
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());
        map.put("user", user);
        return AjaxResultVo.success(map);
    }

    @AppLogin
    @PostMapping("saveUserInfos")
    @ApiOperation("保存个人资料")
    public AjaxResultVo saveUserInfos(UserDTO user, @RequestAttribute("userId") Long userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return AjaxResultVo.error("参数错误");
        }
        user.setUserId(userId);
        userService.update(user);
        return AjaxResultVo.success();
    }

    @AppLogin
    @PostMapping("saveUserAvatar")
    @ApiOperation("修改头像")
    public AjaxResultVo saveUserAvatar(MultipartFile file, @RequestAttribute("userId") Long userId) {
        if (file.isEmpty()) {
            return AjaxResultVo.error("请选择文件！");
        }
        SysUploadFile fileResult = Objects.requireNonNull(OssFactory.init(ossConfig)).uploadFile(file, true);
        UserDTO user = new UserDTO();
        user.setUserId(userId);
        user.setHeadPic(fileResult.getFileUrl());
        userService.update(user);
        AjaxResultVo resultVo = AjaxResultVo.success();
        resultVo.put("headPic", fileResult.getFileUrl());
        return resultVo;
    }

    @AppLogin
    @GetMapping("getUserInfo")
    @ApiOperation("获取个人资料")
    public AjaxResultVo getUserInfo(@RequestAttribute("userId") Long userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return AjaxResultVo.error("参数错误");
        }
        return AjaxResultVo.success(userService.get(userId));
    }

    @AppLogin
    @PostMapping("editPassword")
    @ApiOperation("修改密码")
    public AjaxResultVo editPassword(@RequestBody EditPasswordForm form, @RequestAttribute("userId") Long userId) {
        UserDTO user = userService.get(userId);
        // 旧密码验证
        if (!user.getPassword().equals(DigestUtils.sha256Hex(form.getOldPassword()))) {
            return AjaxResultVo.error("旧的错误密码");
        }
        // 修改密码
        user.setPassword(DigestUtils.sha256Hex(form.getNewPassword()));
        userService.update(user);
        return AjaxResultVo.success();
    }

    @AppLogin
    @PostMapping("saveUserAuth")
    @ApiOperation("保存认证信息")
    public AjaxResultVo saveUserAuth(AuthForm authForm, @RequestAttribute("userId") Long userId) {
        AuthDTO oldAuth = authService.getUserAuthByUserId(userId);
        OssService ossService = Objects.requireNonNull(OssFactory.init(ossConfig));
        AuthDTO newAuth = new AuthDTO();
        if (ObjectUtils.isNotEmpty(authForm.getFrontPic())) {
            SysUploadFile frontFile = ossService.uploadFile(authForm.getFrontPic(), true);
            newAuth.setFrontPic(frontFile.getFileUrl());
        }
        if (ObjectUtils.isNotEmpty(authForm.getBackPic())) {
            SysUploadFile backFile = ossService.uploadFile(authForm.getBackPic(), true);
            newAuth.setBackPic(backFile.getFileUrl());
        }
        newAuth.setIdCard(authForm.getIdCard());
        newAuth.setCityId(authForm.getCityId());
        newAuth.setCityName(authForm.getCityName());
        newAuth.setUserId(userId);
        if (ObjectUtils.isNotEmpty(oldAuth)) {
            newAuth.setId(oldAuth.getId());
            authService.update(newAuth);
        } else {
            authService.add(newAuth);
        }
        // 变更认证状态-->认证中
        UserDTO user = new UserDTO();
        user.setUserId(userId);
        user.setAuthStatus(1);
        userService.update(user);
        return AjaxResultVo.success();
    }

    @AppLogin
    @GetMapping("getUserAuth")
    @ApiOperation("获取认证信息")
    public AjaxResultVo getUserAuth(@RequestAttribute("userId") Long userId) {
        AuthDTO auth = authService.getUserAuthByUserId(userId);
        return AjaxResultVo.success(auth);
    }

}
